;
$(function () {
    var ad = appData(),
        pageNumNow = 1, //当前分页
        tmpObj = {};

    var settingDepart = {
        check: {
            enable: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onClick: departClick
        }
    };
    var settingRole = {
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeClick: beforeClick,
            onCheck: roleCheck
        }
    };

    function departClick(event, treeId, treeNode) {
        showTable(true, 1, treeNode.id);
        $("#departList").val(treeNode.id);
    }

    function beforeClick(treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("role");
        zTree.checkNode(treeNode, !treeNode.checked, null, true);
        return false;
    }

    function roleCheck(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("role");
        var nodes = zTree.getCheckedNodes(true);
        var roleArr = [];
        for (var i = 0; i < nodes.length; i++) {
            roleArr.push(nodes[i].id);
        }
        sessionStorage.roleArr = JSON.stringify(roleArr);
    }

    ad.selectList("U_U_DEPARTTREE", {}, function (data) {
        $.fn.zTree.init($("#depart"), settingDepart, data);
    });

    ad.selectList("U_U_ROLETREE", {}, function (data) {
        $.fn.zTree.init($("#role"), settingRole, data);
    });

    ad.selectList("U_U_ROLELIST", {}, function (data) {
        $("#roleList").empty().append('<option value="">--请选择--</option>').append($.tmpl(tmpObj.list, data));
    });

    ad.selectList("U_U_DEPARTLIST", {}, function (data) {
        $("#departList").empty().append($.tmpl(tmpObj.list, data));
    });

    ad.selectList("U_U_POSITIONLIST", {}, function (data) {
        $("#positionList").empty().append($.tmpl(tmpObj.list, data));
    });

    showTable(true, 1);

    //用户列表
    function showTable(dontRenderPager, page, departmentId) {
        var params = {
            departmentId: departmentId,   //部门ID
            roleId: $("#roleList").val() ? $("#roleList").val() : undefined, //角色ID
            status: $("#userStatus").val() ? $("#userStatus").val() : undefined, //用户状态
            keyWord: $("#search").val() || undefined,   //关键字检索
            page: page, //当前页
            pageSize: appApi("PAGE_SIZE") //每页显示数据条数
        }
        ad.selectList("U_U_LIST", params, function (data) {

            if (data.content.length === 0) {
                $("#userList").empty().append("<tr><td colspan='12' class='colspanCss'><h1>暂无数据</h1></td></tr>");
                return;
            }

            $.each(data.content,function (i,item) {
                item.roleStr=[];
                $.each(item.roles,function () {
                    item.roleStr.push(this.name);
                })
                item.roleStr=item.roleStr.join(",")
            })

            $("#userList").empty().append($.tmpl(tmpObj.userList, data.content));
            editBtn();

            _as.maxL("#userList",10);

            if (dontRenderPager) {
                renderPager(data.totalRecord);
            } else if (data.content.length == 0 && data.totalRecord != 0) {
                $("div.page").find("li.active").prev().addClass("active");
                $("div.page").find("li.active:last").remove();
                pageNumNow = pageNumNow - 1;
                if (pageNumNow == 1) {
                    $("div.page").hide();
                }
                showTable(false, pageNumNow);
            } else if (data.content.length == appApi("PAGE_SIZE") && pageNumNow != 1) {
                renderPager(data.totalRecord, pageNumNow - 1);
            } else if (data.totalRecord <= appApi("PAGE_SIZE")) {
                $("div.page").empty();
            }
        });
    }

    //分页
    function renderPager(totalRecord, nowPage) {
        $("div.page").pagination(totalRecord, appApi("PAGE_SIZE"), {
            callback: function (page_id, jq) {
                pageNumNow = page_id + 1;
                showTable(false, pageNumNow);
            }
        }, nowPage);
    }

    $("#roleList,#userStatus").on("change", function () {
        showTable(true, 1);
    });

    //模糊查询
    $(".icon-search").parent("button").on("click", function () {
        showTable(true, 1);
    });

    $("#search").on('keypress', function (event) {
        if (event.keyCode == "13") showTable(true, 1);
    });

    function checkTree(id) {
        var zTree = $.fn.zTree.getZTreeObj("role");
        var nodes = zTree.getNodesByParam("id", id, null);
        for (var i = 0; i < nodes.length; i++) {
            zTree.checkNode(nodes[i], !nodes[i].checked, null, true);
        }
    }

    function editBtn() {
        $(".table tr").on("click", "td:eq(1) a", function () {

            $("#panel_edite").show()
            var obj = $(this).parents("tr");
            obj.siblings().removeClass("active").end().addClass('active');
            $("#e1").text("编辑用户").attr({ "data-id": obj.find("td:eq(0)").data("id"), "data-rdopid": obj.data("rdopid") });
            $("#e2").val($(this).text());
            $("#password").val(obj.data("userpassword"));
            if (parseInt(obj.find("td:eq(4)").data("sex"))) {
                $("#sex").find("input[type='radio']").eq(1).trigger("click");
            } else {
                $("#sex").find("input[type='radio']").eq(0).trigger("click");
            }
            $("#e3").val(obj.find("td:eq(3)").text());
            $("#e5").val(obj.find("td:eq(5)").find("span").attr("data-original-title"));
            $("#e6").val(obj.find("td:eq(6)").find("span").attr("data-original-title"));
            if (parseInt(obj.find("td:eq(9)").data("status"))) {
                $("input[name='staus']").eq(0).trigger("click");
            } else {
                $("input[name='staus']").eq(1).trigger("click");
            }

            if(obj.data("phoneverify")) {
                $("#phoneVerify").prop("checked",true);
            } else {
                $("#phoneVerify").prop("checked",false);
            }

            var ipVerifyArray =  obj.data("ipverify"),ipVerifyArrayL = ipVerifyArray.length;
            $("#ipVerify").empty();
            if(ipVerifyArrayL==0) $("#ipchk").prop("checked",false);

            for (var i = 0; i < ipVerifyArray.length; i++) {
                if(i==0) {
                    $("#ipVerify").append("<p><span><input class='input checkboxte' type='text' placeholder='起始IP' value='"+ipVerifyArray[i][0]+"' disabled>.<input disabled class='input checkboxte' type='text' placeholder='结束IP' value='"+ipVerifyArray[i][1]+"'></span><i class='icon-add-circle' ></i></p>");
                    $("#ipchk").prop("checked",true);
                }else {
                    $("#ipVerify").append("<p><span><input class='input checkboxte' type='text' placeholder='起始IP' value='"+ipVerifyArray[i][0]+"' disabled>.<input disabled class='input checkboxte' type='text' placeholder='结束IP' value='"+ipVerifyArray[i][1]+"'></span><i class='icon-cancel'></i></p>");
                }
            }

            $("#departList").val(obj.find("td:eq(7)").data("departmentid"));
            $("#positionList").val(obj.find("td:eq(8)").data("positionid"));
            $("#staus").show();
           // $(".btnadd").css("display", "inline-block");
            $("#add").hide();
            $("#modify").show();

            resetTree();
            var roleArr = obj.data("roles");
            $.each(roleArr, function (i, n) {
                checkTree(n.id);
            })
        });

        $(".icon-pencil").on("click", function () {
            $(this).parents("tr").find("a").trigger("click");

        });

        $(".btnadd").off("click").on("click", function () {
            $(".table tr").removeClass('active');
            $("#e1").text("添加新用户");
            $("#staus").hide();
            $(".form-box input").val("");
            $(this).hide();
            $("#add").show();
            $("#modify").hide();

            $("#phoneVerify").prop("checked",false);
            $("#ipchk").prop("checked",false);
            $("#ipVerify").empty();
        });

        $(".icon-trashcan").on("click", function () {
            var uid = $(this).parents("tr").attr("data-id");
            var id = $(this).parents("tr").find("td:eq(1)").text();
            _as.jConfirm("<p>确定要删除用户 " + id + " 吗？</p>", function (obj) {
                ad.del("U_U_DELETE", { id: uid }, function () {
                    showTable(true, 1);
                    $(".btnadd").trigger("click");
                    _as.jAlert("<p>用户删除成功</p>");
                });
            });
        });
    }

    $("#ipVerify").on("click", "i.icon-add-circle", function() {
        $("#ipVerify").append("<p><span><input class='input checkboxte' type='text' placeholder='起始IP'>.<input class='input checkboxte' type='text' placeholder='结束IP'></span><i class='icon-cancel'></i></p>");
    })

    $("#ipVerify").on("click", "i.icon-cancel", function() {
        $(this).parent().remove();
    })

    $("#ipchk").on("change", function() {
        if($(this).is(":checked")) {
            $("#ipVerify").append("<p><span><input class='input checkboxte' type='text' placeholder='起始IP'>.<input class='input checkboxte' type='text' placeholder='结束IP'></span><i class='icon-add-circle'></i></p>");
        }else {
            $("#ipVerify").empty();
        }
    })

    function validate() {
        var onoff = true,
            arr = $.makeArray($(".form-box .fc-danger").parents(".form-item").find("input,textarea").not("input[type='radio']").not("input[type='checkbox']")).reverse();
        $.each(arr, function (index, ele) {
            if (!$(this).val()) {
                $(this).focus();
                onoff = false;
            }
        })
        if(!sessionStorage.roleArr) {
            _as.jAlert("<p>请至少选择一个角色！</p>");
            onoff = false;
        }
        return onoff;
    }

    function resetTree() {
        var zTree = $.fn.zTree.getZTreeObj("role");
        zTree.checkAllNodes(false);
    }

    $("thead").find("input[type='checkbox']").on("click", function () {
        $("tbody").find("input[type='checkbox']").prop("checked", $(this).prop("checked"));
    })

    $("#add").on("click", function () {
        var ipVerifyL=[];
        $("#ipVerify").find("p").each(function(index, el) {
            var a = $(this).find("input:eq(0)").val(),b = $(this).find("input:eq(1)").val();
            ipVerifyL.push([a,b]);
        });
        if (validate()) {
            var params = {
                account: $("#e2").val(),
                password: $("#password").val(),
                name: $("#e3").val(),
                sex: $("#sex input:checked").data("sex"),
                phone: $("#e5").val(),
                mail: $("#e6").val(),
                remarks: $("#e7").val() || undefined,
                departmentId: $("#departList option:selected").val(),
                positionId: $("#positionList option:selected").val(),
                roleIds: JSON.parse(sessionStorage.roleArr),
                verify_type: $("#e5").val(),
                verify_value: $("#e5").val(),
                phoneVerify:$("#phoneVerify").is(":checked")?1:0,
                ipVerify:ipVerifyL
            };
            ad.insert("U_U_ADD", params, function () {
                showTable(true, 1);
                $(".btnadd").trigger("click");
                resetTree();
                _as.jAlert("<p>用户添加成功</p>");
                sessionStorage.roleArr=[];
            });
        }
    });

    $("#modify").on("click", function () {
        var ipVerifyL=[];
        $("#ipVerify").find("p").each(function(index, el) {
            var a = $(this).find("input:eq(0)").val(),b = $(this).find("input:eq(1)").val();
            ipVerifyL.push([a,b]);
        });
        if (validate()) {
            var params = {
                id: $("#e1").attr("data-id"),
                account: $("#e2").val(),
                password: $("#password").val(),
                name: $("#e3").val(),
                sex: $("#sex input:checked").data("sex"),
                phone: $("#e5").val(),
                mail: $("#e6").val(),
                status: $("#staus input:checked").data("status"),
                remarks: $("#e7").val() || undefined,
                departmentId: $("#departList option:selected").val(),
                positionId: $("#positionList option:selected").val(),
                roleIds: JSON.parse(sessionStorage.roleArr),
                rdopId: $("#e1").attr("data-rdopid"),
                verify_type: $("#e5").val(),
                verify_value: $("#e5").val(),
                phoneVerify:$("#phoneVerify").is(":checked")?1:0,
                ipVerify:ipVerifyL
            };
            ad.update("U_U_MODIFY", params, function () {
                showTable(true, 1);
                $(".btnadd").trigger("click");
                resetTree();
                _as.jAlert("<p>用户修改成功</p>");
                sessionStorage.roleArr=[];
            });
        }
    });

    $("#deleteList").on("click", function () {
        var idList = [];
        $("#userList").find("input[type='checkbox']").each(function (i, n) {
            if ($(this).prop("checked") === true) {
                idList.push($(this).parents("tr").find("td:eq(1)").data("id"));
            }
        });

        if (idList.length > 0) {
            _as.jConfirm("<p>确定要批量删除用户吗？</p>", function (obj) {
                ad.selectList("U_U_LISTDELETE", { ids: idList.join(",") }, function () {
                    showTable(true, 1);
                    $(".btnadd").trigger("click");
                    $("thead").find("input[type='checkbox']").prop("checked", false);
                    _as.jAlert("<p>批量删除用户成功</p>");
                });
            });
        }
    });

    (function getTemp() {
        tmpObj.userList = "<tr data-id=\"{{= id}}\" data-userpassword=\"{{= password}}\" data-roles=\'{{= JSON.stringify(roles)}}\' data-rdopid=\"{{= rdopId}}\" "+
"data-phoneVerify=\"{{= phoneVerify}}\" "+
"data-ipVerify=\"{{= JSON.stringify(ipVerify)}}\">"+

"    <td data-id=\"{{= id}}\">{{= num}}</td>"+
"    <td><a href=\"javascript:void(0);\">{{= account}}</a></td>"+
"    <td>"+
"        <span class=\"maxL\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"{{= roleStr}}\">{{= roleStr}}</span>"+
"    </td>"+
"    <td>{{= name}}</td>"+
"    {{if sex==1}}"+
"    <td data-sex=\"{{= sex}}\">男</td>"+
"    {{else}}"+
"    <td data-sex=\"{{= sex}}\">女</td>"+
"    {{/if}}"+
"    <td>"+
"        <span class=\"maxL\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"{{= phone}}\">{{= phone}}</span>"+
"    </td>"+
"    <td>"+
"        <span class=\"maxL\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"{{= mail}}\">{{= mail}}</span>"+
"    </td>"+
"    <td data-departmentid=\"{{= departmentId}}\">"+
"        <span class=\"maxL\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"{{= departmentName}}\">{{= departmentName}}</span>"+
"    </td>"+
"    <td data-positionid=\"{{= positionId}}\">{{= positionName}}</td>"+
"    {{if status==1}}"+
"    <td data-status=\"{{= status}}\"><span class=\"badge badge-success\">正常</span></td>"+
"    {{else}}"+
"    <td data-status=\"{{= status}}\"><span class=\"badge badge-warning\">停止</span></td>"+
"    {{/if}}"+
"    <td>"+
"        <p class=\"table-icons\"><a href=\"javascript:void(0);\"><i class=\"icon-pencil\" title=\"编辑\"></i></a>"+
"        <a href=\"javascript:void(0);\" style='display: none'><i class=\"icon-trashcan\" title=\"删除\" ></i></a>"+
"        </p>"+
"    </td>"+
"</tr>";
        tmpObj.list = "\n<option value=\"{{= id}}\">{{= name}}</option>\n";
    })();
});